package org.jeecg.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.app.annotation.Encode;
import org.jeecg.modules.app.body.ParamMap;
import org.jeecg.modules.app.handler.BaseHandler;
import org.jeecg.modules.app.handler.ConfigHandler;
import org.jeecg.modules.app.handler.UserHandler;
import org.jeecg.modules.app.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * APP测试接口
 */
@CrossOrigin(origins = "*", maxAge = 3600, methods = {RequestMethod.POST, RequestMethod.GET})
@RestController
@RequestMapping("/app/")
@Api("APP接口")
public class AppController {

    @Autowired
    private RedisUtil redisUtil;

    private BaseHandler mHandler;


    @RequestMapping(value = "api/{method}", method = RequestMethod.POST)
    @ResponseBody
    @Encode
    public JSONObject findMainData(@RequestBody ParamMap paramMap, @PathVariable(name = "method", required = false) String method, HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*如果不是login 就走token认证，如果是则跳过*/
        String token = request.getHeader("token");
       if (!"login".equals(method) && !"update".equals(method)) {
            if (!redisUtil.hasKey(token)) {
                return JsonUtil.errorJson(401, "登陆失效");
            }
        }
        switch (method) {
            case "login":
                mHandler = new UserHandler(token);
                return mHandler.checkApi(paramMap, method);
            case "update":
                mHandler = new ConfigHandler(token);
                return mHandler.checkApi(paramMap, method);

        }
        return JsonUtil.errorJson("访问地址错误");
    }
}
